#include <stdio.h>
#include <stdlib.h>	/* exit() */
#include <string.h>
#include <pthread.h>
#include <sys/time.h>
#include <time.h>
#include <limits.h>
#include <errno.h>
#include <signal.h>
#include <fcntl.h>
#include <unistd.h>


/*
 * fork 函数示例
 */


int glob = 6;	/* external variable in initialized data */
char buf[] = "a write to stdout\n";

int main(void)
{
	int var;	/* automatic variable on the stack */
	pid_t pid;

	var = 88;
	if (write(STDOUT_FILENO, buf, sizeof(buf) - 1) != sizeof(buf) - 1)
		perror("write error");

	printf("before fork\n");	/* we don't flush stdout */

	if (( pid = fork()) < 0) 
		perror("fork error");
	else if (pid == 0) {	/* child */
		glob++;				/* modify variables */
		var++;
	}
	else
		sleep(2);	/* parent */

	printf("pid = %d, glob = %d, var = %d\n", getpid(), glob, var);

	exit(0);
}

/*

result:

 pid = 3243, glob = 7, var = 89
 pid = 3242, glob = 6, var = 88

子进程对变量所作的改变并不影响父进程中该变量的值.

*/
